<template>
  <div class="app-container">
    <div class="work-container">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card>
            <div class="video-container">
              <div class="video-area" v-if="!cameraOpened">
                <div class="no-signal">NO SIGNAL</div>
              </div>
              <video ref="videoRef" width="100%" height="400" autoplay v-show="cameraOpened"></video>
              <div class="camera-controls">
                <el-button 
                  type="primary" 
                  icon="VideoCamera" 
                  @click="openCamera" 
                  v-if="!cameraOpened"
                  class="camera-button"
                >
                  开启摄像头
                </el-button>
                <el-button 
                  type="primary" 
                  icon="Close" 
                  @click="closeCamera" 
                  v-if="cameraOpened"
                  class="camera-button"
                >
                  关闭摄像头
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const videoRef = ref(null)
const cameraOpened = ref(false)
let stream = null

function openCamera() {
  navigator.mediaDevices.getUserMedia({ video: true })
    .then(mediaStream => {
      stream = mediaStream
      videoRef.value.srcObject = stream
      cameraOpened.value = true
    })
    .catch(err => {
      cameraOpened.value = false
      alert('无法打开摄像头: ' + err)
    })
}

function closeCamera() {
  if (stream) {
    stream.getTracks().forEach(track => track.stop())
    stream = null
  }
  videoRef.value.srcObject = null
  cameraOpened.value = false
}

onMounted(() => {
  // 页面加载时不自动开启摄像头
})
</script>

<style scoped>
.work-container {
  padding: 20px;
}

.video-container {
  position: relative;
  width: 100%;
  height: 400px;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.video-area {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eee;
}

.no-signal {
  font-size: 36px;
  color: #333;
  font-weight: bold;
}

.camera-controls {
  position: absolute;
  bottom: 20px;
  display: flex;
  justify-content: center;
  width: 100%;
}

.camera-button {
  margin: 0 10px;
}
</style>